<?php

namespace app\controller\open;

use app\service\AliyunCloudStorageService;
use app\service\AliyunProjectService;
use app\service\AliyunService;
use app\service\DeviceBaseService;
use app\service\OpenAppOrderService;
use app\service\UserDeviceBindingService;
use app\validate\PageValidate;
use app\validate\OssOrderValidate;
use share\service\ContextService;
use share\service\UserBaseService;
use share\service\UserBindService;
use share\utils\Helper;
use think\Log;

class OssOrderController extends BaseOpenController{

    protected $beforeActionList = [
        "checkOpenAppSign",
    ];

    public function initValidate(){        
        $this->validate = new OssOrderValidate();
    }

    public function list_action(){  
        $input = $this->check('open_list');
        $page = $this->check('pageInfo',null,(new PageValidate()));
        $openAppId = $openAppId = $this->openApp['id'];
        $data = OpenAppOrderService::getOrderList($openAppId,$input,$page['page'],$page['size']);
        $listData = $data['list'];
        $list  = [];
        foreach($listData as $item){
            $list[] = self::formatOrderDetailInfo($item);
        }
        return self::ok(self::formatPageData($page,$data['total'],$list));
    }

    public function detail_action(){  
        $input = $this->check('open_detail');
        $openAppId = $openAppId = $this->openApp['id'];
        $data = OpenAppOrderService::getOrderDetail($openAppId,$input);    
        return self::ok(self::formatOrderDetailInfo($data['order'],$data['detail'],$data['payed']));    
    }

    /**
     * 下单  下单时检查用户是否可以购买套餐
     */
    public function create_action(){
        $input = $this->check('open_create');
        if(isset($input['extend'])){
            $input['extend'] = $this->check('open_create_extend',$input['extend']);
        }
        $openAppId = $openAppId = $this->openApp['id'];
        $data = OpenAppOrderService::create($openAppId,$input);
        return self::ok(self::formatOrderDetailInfo($data['order'],$data['detail']));
    }

    /**
     * 购买  
     */
    public function buy_action(){
        $input = $this->check();
        $openAppId = $openAppId = $this->openApp['id'];
        $data = OpenAppOrderService::buy($openAppId,$input['out_trade_no']);
        return self::ok($data);
    }

    /**
     * 下单并购买  
     */
    public function create_and_buy_action(){
        $input = $this->check();
        $openAppId = $openAppId = $this->openApp['id'];
        $data = OpenAppOrderService::createAndBuy($openAppId,$input);
        return self::ok($data);
    }

    /**
     * 设备的已购套餐列表信息
     */
    public function payed_product_action(){
        $input = $this->check();
        $openAppId = $openAppId = $this->openApp['id'];
        $data = OpenAppOrderService::payedInfo($openAppId,$input['sn']);
        return self::ok($data);
    }

    /**
     * 激活 立即激活某个套餐
     */
    public function use_action(){
        $input = $this->check();
        $openAppId = $openAppId = $this->openApp['id'];
        $data = OpenAppOrderService::immediateUse($openAppId,$input);
        return self::ok($data);
    }

    /**
     * 用户设备 是否可以购买
     */
    public function is_can_buy_action(){
        $input = $this->check();
        $openAppId = $openAppId = $this->openApp['id'];
        $sn = $input['sn'];
        $device = DeviceBaseService::getUsefulOssSn($sn);
        $res = [
            'ret' => 1,
        ];
        if(empty($device)){
            $res = [
                'ret' => 0,
                'msg' => 'device not found!',
            ];
            return self::ok($res);
        }

        $project = AliyunProjectService::fastGetById($device['aliyun_project_id']);
        if(empty($project)){
            $res = [
                'ret' => 0,
                'msg' => 'AliyunProject ['.$device['aliyun_project_id'].'] no set or deleted !',
            ];
            return self::ok($res);
        }

        $bind = UserDeviceBindingService::getBindingInfoByIotId($device['iot_id']);
        if(empty($bind)){
            $res = [
                'ret' => 0,
                'msg' => 'device not bind!',
            ];
            return self::ok($res);
        }
        $userInfo = UserBaseService::getBase($bind['uid']);

        if(empty($userInfo) || $userInfo['user_id'] != $input['user_id']){
            $res = [
                'ret' => 0,
                'msg' => 'device bind user not match!',
            ];
            return self::ok($res);
        }

        // $cloudStorage = AliyunCloudStorageService::getByFilter([
        //     'site' => $device['server_site'],
        // ]);

        $service = AliyunService::instance($project['project_key'],$device['server_site']);
        $resp = $service->isCanBuyCloudStorage($device['iot_id'],
            AliyunCloudStorageService::DEFAULT_CLOUD_RESOURCE,
            AliyunCloudStorageService::DEFAULT_EVENT_RESOURCE
        );
        trace("aliyunResp".json_encode($resp),Log::ERROR);
        if($resp && isset($resp['available']) && $resp['available'] ){
            return self::ok($res);
        }
        else{
            $res = [
                'ret' => 0,
                'msg' => 'aliyun api not allow to buy !',
            ];
            return self::ok($res);
        }       
    }

    public static function formatOrderDetailInfo($order,$orderDetail  = null,$payed = null){        
        $orderIgnoreKeys  = ['prodoct_id','aliyun_cloud_storage_id','open_app_id'];
        foreach($orderIgnoreKeys as $key){
            unset($order[$key]);
        }
        if($orderDetail){
            $orderDetailIgnoreKeys  = ['id','oss_order_id','oss_product_id','immediate_use','user_id'];
            foreach($orderDetailIgnoreKeys as $key){
                unset($orderDetail[$key]);
            }
            $orderDetail['product_sku'] = $orderDetail['oss_product_sku'];
            $orderDetail['product_name'] = $orderDetail['oss_product_name'];
            unset($orderDetail['oss_product_sku']);
            unset($orderDetail['oss_product_name']);
            $orderInfo = array_merge($orderDetail,$order);
        }
        else{
            $orderInfo  = $order;
        }  
        return Helper::arrayUnderscoreToCamelKey($orderInfo);
    }


}